#include "chatwidget.h"
#include <QTimer>
#include <QDebug>
#include <QTextDocumentFragment>

ChatWidget::ChatWidget(QWidget *parent)
        : QPlainTextEdit(parent)
{
    this->posForNextFinishedMsg = 0;
    this->x = 0; //<-- remove. debug shit
    this->setCenterOnScroll(true);
    this->remoteTag = tr("<font color=\"red\">&lt;remote&gt;</font>: ");
    this->localTag = tr("<font color=\"orange\">&lt;local&gt;</font>: ");
    this->appendHtml(this->remoteTag);
    this->appendHtml(this->localTag);

    QObject::connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(cursorMoved()));

    //this->posRemoteStart = 1;
    this->remoteCursor = new QTextCursor(this->document());

    //TODO: unhardcode
    this->remoteCursor->setPosition(10);

    this->localCursor = new QTextCursor(this->document());
    this->localCursor->setPosition(this->textCursor().position());

    //QTimer::singleShot(3000, this, SLOT(demoRemoteMessage()));
}

void ChatWidget::demoRemoteMessage()
{
    QString msg = "Hi, this is a remote message getting fired. ";
    if(this->x >= msg.length())
    {
        this->remoteFinish();
        this->x = 0;
        QTimer::singleShot(5000, this, SLOT(demoRemoteMessage()));
    }
    else
    {
        this->remoteWrite(msg.at(this->x));
        this->x++;
        QTimer::singleShot(100, this, SLOT(demoRemoteMessage()));
    }
}

void ChatWidget::cursorMoved()
{
    //qDebug() << "Cursor at end?: " << this->textCursor().atEnd();
    if(this->textCursor().atEnd() == false)
    {
        QTextCursor newCursor(this->textCursor());
        newCursor.setPosition(this->toPlainText().length());
        this->setTextCursor(newCursor);
    }
}

void ChatWidget::remoteBackspace()
{
    this->remoteCursor->deletePreviousChar();
}

void ChatWidget::remoteWrite(QChar msg)
{
    this->remoteWrite((QString) msg);
}

void ChatWidget::remoteWrite(QString text)
{
    this->remoteCursor->insertText(text);
}

void ChatWidget::remoteFinish()
{
    this->remoteCursor->insertHtml("<br />");
    //the message is already in the correct location (i hope :P)
    this->posForNextFinishedMsg = this->remoteCursor->position();
    this->remoteCursor->insertHtml(this->remoteTag);
}

void ChatWidget::localFinish()
{
    //we got to move it to posForNextFinishedMsg
    int charsToMove = this->textCursor().position() - this->remoteCursor->position() - 1;

    Q_ASSERT(charsToMove > 0);

    this->localCursor->setPosition(this->textCursor().position());
    this->localCursor->movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, charsToMove);

    QString txt = this->localCursor->selection().toPlainText();
    Q_ASSERT(this->localCursor->hasSelection());
    this->localCursor->removeSelectedText();

    this->localCursor->setPosition(this->posForNextFinishedMsg);

    QString html = "<font color=\"green\">" + Qt::escape(txt).replace("\n","<br />") + "</font><br />";
    this->localCursor->insertHtml(html);

    this->posForNextFinishedMsg = this->localCursor->position();

    this->textCursor().insertHtml(this->localTag);

}

void ChatWidget::keyPressEvent(QKeyEvent *event)
{
    if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() != Qt::ShiftModifier)
    {
            this->localFinish();
            emit this->finishedMsg();
    }
    else if(event->key() == Qt::Key_Backspace)
    {
        QPlainTextEdit::keyPressEvent(event);
        emit this->typedBackspace();
    }
    else if(event->key() == Qt::Key_Delete)
    {
        QPlainTextEdit::keyPressEvent(event);
        emit this->typedDelete();
    }
    else
    {
        int beforePosition = this->textCursor().position();
        QPlainTextEdit::keyPressEvent(event);
        int moved = this->textCursor().position() - beforePosition;
        if(moved == 1)
            emit this->typedChar(event->text().at(0));
        else if(moved == 0)
            ;
        else
            qFatal("Cursor moved more than 1 place?");
    }
}

void ChatWidget::insertFromMimeData(const QMimeData *source)
{
    //TODO: allow file transfers
}
